package com.sbm.datasource.dynamic;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class DynamicDataSourceSwitcher {
    private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSourceSwitcher.class);

    public void switchTo(String dataSource) {
        if (DynamicDataSourceHolder.containsDataSource(dataSource)) {
            LOGGER.info("切换到数据源[" + dataSource + "]");
            DynamicDataSourceHolder.setCurrentDataSource(dataSource);
        } else
            LOGGER.error("数据源[" + dataSource + "]不存在，使用默认数据源");
    }

    public void switchTo(JoinPoint joinPoint) {
        switchTo(getDynamicDataSourceTarget(joinPoint));
    }

    public void switchTo(DynamicDataSourceTarget target) {
        switchTo(getDataSource(target));
    }

    public void backFrom(String dataSource) {
        if (DynamicDataSourceHolder.containsDataSource(dataSource)) {
            LOGGER.info("从[" + dataSource + "]返回到默认数据源");
            DynamicDataSourceHolder.clearCurrentDataSource();
        }
    }

    public void backFrom(JoinPoint joinPoint) {
        backFrom(getDynamicDataSourceTarget(joinPoint));
    }

    public void backFrom(DynamicDataSourceTarget target) {
        backFrom(getDataSource(target));
    }

    private DynamicDataSourceTarget getDynamicDataSourceTarget(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        return method.getAnnotation(DynamicDataSourceTarget.class);
    }

    private String getDataSource(DynamicDataSourceTarget target) {
        return target.value();
    }
}
